package com.qqt.csr.archive.batch.task;

import cn.hutool.json.JSONUtil;
import com.qqt.csr.archive.model.ConversationEndMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.qqt.csr.archive.batch.task.constants.ParamConstant.CONVERSATION_IDS;
import static com.qqt.csr.archive.batch.task.constants.ParamConstant.SOURCE;

/**
 * @Author: yang hao
 * @Date: 2024/12/2 14:41
 * @Description: 归档任务 启动器
 **/
@Slf4j
@Component
public class ArchiveRunner {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    private Job archiveJob;

    /**
     * 启动任务
     * @param message {@link ConversationEndMessage} 会话结束事件
     */
    public void run(ConversationEndMessage message) {
        // 根据会话分配线程，创建会话结束事件任务链
        List<String> conversationIds = message.getConversationIds();
        String conversationIdsJson = JSONUtil.toJsonStr(conversationIds);
        // 创建会话任务参数
        JobParameters params = new JobParametersBuilder()
                .addString(CONVERSATION_IDS, conversationIdsJson)
                .addString(SOURCE, message.getSource().name())
                .toJobParameters();
        try {
            // 启动任务
            jobLauncher.run(archiveJob, params);
            log.debug("会话结束事件任务链创建成功，会话ID:{}", conversationIdsJson);
        } catch (JobExecutionAlreadyRunningException e) {
            log.warn("会话结束事件任务链已运行，会话ID:{}", conversationIdsJson);
        } catch (JobRestartException e) {
            log.warn("会话结束事件任务链重启失败，会话ID:{}", conversationIdsJson);
        } catch (JobInstanceAlreadyCompleteException e) {
            log.warn("会话结束事件任务链已结束，会话ID:{}", conversationIdsJson);
        } catch (JobParametersInvalidException e) {
            log.warn("会话结束事件任务链参数校验失败，会话ID:{}", conversationIdsJson);
        }
    }

}
